const puppeteer = require('puppeteer');

const MaxBrowserNum = 2
/**
 * [{browserWSEndpoint: '', tabNumber: 0}] browserWSEndpoint =》浏览器标识, tabNumber 打开的tab页面数目
 * */
let WSE_LIST = []

function createBrowser() {
    (async () => {
        for(let i = 0; i < MaxBrowserNum; i++) {
            const browser = await puppeteer.launch({
                headless: true,
                devtools: false,
                defaultViewport: {
                    width: 1920,
                    height: 1080
                },
                args: ['--no-sandbox', '--disable-setuid-sandbox', '--app-cache-force-enabled']
            })
            const browserWSEndpoint = await browser.wsEndpoint();
            WSE_LIST[i] = {
                browserWSEndpoint,
                tabNumber: 0
            }
        }
    })()
}
createBrowser()

module.exports = {

    getHtml: async function (url) {
        const dataSort = WSE_LIST.sort((prev, next) => {
            return prev.tabNumber - next.tabNumber
        })
        const data = dataSort[0]
        const browser = await puppeteer.connect({
            defaultViewport: {
                width: 1920,
                height: 1080
            },
            browserWSEndpoint: data.browserWSEndpoint
        })
        WSE_LIST = WSE_LIST.map(item => {
            if(item.browserWSEndpoint === data.browserWSEndpoint) {
                ++item.tabNumber
            }
            return item
        })
        try {
            const page = await browser.newPage();
            await page.setCacheEnabled(true)

            const blockTypes = ['image', 'media', 'font', 'manifest', 'other', 'texttrack', 'websocket'];
            await page.setRequestInterception(true); //开启请求拦截
            page.on('request', async request => {
                const type = request.resourceType();
                if (blockTypes.indexOf(type) > -1) {
                    //直接阻止请求
                    return request.abort();
                } else {
                    return request.continue({
                        headers: Object.assign({}, request.headers(), {
                            'ppt': 'true'
                        })
                    });
                }
            });
            //响应
            page.on('response', async response => {
                // console.info(await response.url() + ' ' + await response.request().method() + ' ' + await response.status() + ' ' + await response.request().resourceType())
                // logger.info(await response.url() + ' ' + await response.request().method() + ' ' + await response.status() + ' ' + await response.request().resourceType());
            });


            await page.goto(url, {
                waitUntil: ['domcontentloaded', 'networkidle0'] // networkidle0 暂时去掉
            })
            const html = await page.content();
            await page.close()
            browser.disconnect()
            WSE_LIST = WSE_LIST.map(item => {
                if(item.browserWSEndpoint === data.browserWSEndpoint) {
                    --item.tabNumber
                }
                return item
            })
            return html
        }
        catch (e) {
            // await browser.close();
        }
    }
}
